import Vue from "vue"
import Vuex from "vuex"


Vue.use(Vuex)


const state = {
	// 伪数组 carts ={'gid':{count:1,goods:{}}} {'1',{goods:{...}}}
	carts: {},

};
const mutations = {
	addOne(state, gd) {
		//先去localstorage看下有无加购记录,有,显示出来,没有默认null创建一个对象.
		if (localStorage.getItem("carts")) {
			state.carts = JSON.parse(localStorage.getItem("carts"))
		}
		//2看下这个商品是否购买过,购买过,数量加1,没有,创建对象进去
		if (state.carts[gd.ID]) {
			state.carts[gd.ID].count++
		} else {
			state.carts[gd.ID] = {
				count: 1,
				goods: gd
			}
		}
		localStorage.setItem("carts", JSON.stringify(state.carts))
		console.log("购买一个" + gd.name + "成功")
		state.carts = JSON.parse(localStorage.getItem("carts"))
	},
	showcar(state) {
		state.carts = JSON.parse(localStorage.getItem("carts"))
	},
	shopcarNum(state) {
		localStorage.setItem("carts", JSON.stringify(state.carts))
	}
}
const actions = {
	addTo(context, goods) {
		context.commit("addOne", goods)
	},
	viewCart(context) {

		context.commit("showcar")
	},
	toshopcarNum(context) {
		context.commit("shopcarNum")
	}
}
const store = new Vuex.Store({
	state,
	mutations,
	actions
});
export default store;
